package com.tiancikeji.zaoke.app.dao.ticket.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.tiancikeji.zaoke.app.dao.ticket.TicketDao;
import com.tiancikeji.zaoke.app.model.user.Ticket;

public class TicketDaoImpl extends JdbcDaoSupport implements TicketDao{

	private static final String TABLE = "`zaoke`.`ticket`";
	private static final String QUERY_VIEW = "`id`, `user_id`, `cell_phone`, `ticket`, `add_userid`, `add_time`";

	public Ticket getTicketByUser(long userid, String ticket){
		String sql = "select " + QUERY_VIEW + " from " + TABLE + " where `user_id` = ? and `ticket` = ? order by add_time desc limit 1";
		
		List<Ticket> tickets = getJdbcTemplate().query(sql, new Object[]{userid, ticket}, new RowMapper<Ticket>() {

			public Ticket mapRow(ResultSet rs, int rowNum) throws SQLException {
				Ticket ticket = new Ticket();
				ticket.setId(rs.getLong("id"));
				ticket.setUserId(rs.getLong("user_id"));
				ticket.setCellPhone(rs.getString("cell_phone"));
				ticket.setTicket(rs.getString("ticket"));
				ticket.setAddUserId(rs.getLong("add_userid"));
				ticket.setAddTime(rs.getDate("add_time"));
				return ticket;
			}
		});
		
		if(tickets != null && tickets.size() > 0)
			return tickets.get(0);
		else
			return null;
	}

	public boolean addTicket(Ticket ticket) {
		String sql = "insert into " + TABLE + "(user_id, cell_phone, ticket, add_userid, add_time) values(?, ?, ?, ?, ?)";
		return getJdbcTemplate().update(sql, new Object[]{ticket.getUserId(), ticket.getCellPhone(), ticket.getTicket(), ticket.getAddUserId(), ticket.getAddTime()}) > 0;
	}
}
